"""
 DRF调用序列化器，在函数上方添加@apiview，可自动绕过csrf_token
 DRF支持get、post、put、delete
 获取数据: request.data
"""
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response

from .models import News, Category
from .serializers import NewsSerializer, CategorySerializer, NewsGetSerializer, CategoryGetSerializer

@api_view(['GET'])
def getNews(request:Request):
    queryset = News.objects.select_related('category')
    serializer = NewsGetSerializer(instance=queryset, many=True)
    return Response(serializer.data,status=200)
@api_view(['GET'])
def getNew(request:Request,pk):
    new = News.objects.get(pk=pk)
    serializer = NewsGetSerializer(instance=new)
    return Response(serializer.data,status=200)
@api_view(['POST'])
def insertNews(request:Request):
    serializer = NewsSerializer(data=request.data)
    # 有异常抛出
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=200)
    return Response(serializer.errors,status=404)

@api_view(['PUT'])
def updateNews(request:Request,pk):
    instance = News.objects.get(pk=pk)
    serializer = NewsSerializer(instance=instance,data=request.data)
    # 有异常抛出
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=200)
    return Response(serializer.errors, status=404)


@api_view(['DELETE'])
def delNews(request:Request,pk):
    queryset=News.objects.filter(pk=pk)
    if queryset.exists():
        queryset.first().delete()
        return Response({'code': 200, 'msg': '删除成功'}, status=200)
    return Response({'code': 200, 'msg': '删除失败'}, status=404)

@api_view(['GET'])
def getCategorys(request:Request):
    queryset = Category.objects.prefetch_related('news')
    serializer = CategoryGetSerializer(instance=queryset, many=True)
    return Response(serializer.data, status=200)